package com.azt.front.interceptor;

import com.azt.front.permission.ClearRequire;
import com.azt.front.permission.RequireGuest;
import com.azt.front.utils.ContextUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器
 * Created by shangwq on 2016/8/7.
 */
public class RequireGuestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            RequireGuest requireGuest = handlerMethod.getMethodAnnotation(RequireGuest.class);
            ClearRequire clearRequire = handlerMethod.getMethodAnnotation(ClearRequire.class);
            if(clearRequire == null && requireGuest == null) {
                requireGuest = handlerMethod.getBean().getClass().getAnnotation(RequireGuest.class);
            }

            if(requireGuest != null && ContextUtil.isLogined()) {
                //当前已经登录，验证失败
                response.sendRedirect("/");
                return false;
            }
        }
        return true;
    }
}
